package com.easymin.weixin.controller.v4;

import com.easymin.weixin.common.api.DaijiaApi;
import com.easymin.weixin.common.api.PassengerApi;
import com.easymin.weixin.common.api.SalesApi;
import com.easymin.weixin.entity.WxApplication;
import com.easymin.weixin.entity.sales.Coupon;
import com.easymin.weixin.manager.WxApplicationManager;
import com.easymin.weixin.manager.ZhuancheManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import javax.swing.JEditorPane;

@SuppressWarnings("all")
@RestController("zhuancheResV4")
@RequestMapping("api/zhuanche/v4")
public class ZhuancheRes {
  @Autowired
  private ZhuancheManager zhuancheManager;
  @Autowired
  private WxApplicationManager wxApplicationManager;
  @Autowired
  private DaijiaApi daijiaApi;
  @Autowired
  private SalesApi salesApi;
  @Autowired
  private PassengerApi passengerApi;

  /**
   * V4查询单个订单.
   */
  @RequestMapping(value = {"findOne"}, method = RequestMethod.GET)
  public ResultTransport findOne(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport =
        zhuancheManager.findOneV4(orderId, wxApplication.getAddress(), appKey);
    return resultTransport;
  }

  /**
   * V4查询专车类型.
   */
  @RequestMapping(value = {"queryType"}, method = RequestMethod.GET)
  public ResultTransport queryType(
      @RequestParam("companyId") Long companyId,
      @RequestParam("appKey") String appKey) {

    ResultTransport resultTransport = zhuancheManager.queryTypeV4(companyId, appKey);
    return resultTransport;
  }

  /**
   * V4查询单个服务人员.
   */
  @RequestMapping(value = {"findEmployByToken"}, method = RequestMethod.GET)
  public ResultTransport findEmployByToken(
      @RequestParam("employToken") String employToken,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);

    return resultTransport;
  }

  /**
   * V4抢单.
   */
  @RequestMapping(value = {"grab"}, method = RequestMethod.POST)
  public ResultTransport grab(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employToken") String employToken,
      @RequestParam(required = false ,value= "rentalCompanyId") Long rentalCompanyId,
      @RequestParam(required = false ,value= "rentalCompanyName") String rentalCompanyName,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();
    
    Long employId = Long.valueOf(emap.get("employId").toString());
    Long companyId = Long.valueOf(emap.get("companyId").toString());
    Double employScore = Double.valueOf(emap.get("employScore").toString());
    String employName = (String) emap.get("employName");
    String employPhone = (String) emap.get("employPhone");
    String employAccount = (String) emap.get("employAccount");
    String employPhoto = (String) emap.get("employPhoto");
    int employJobStatus = (int) emap.get("employJobStatus");
    int employStatus = (int) emap.get("employStatus");
    String employJobType = (String) emap.get("employJobType");
    ResultTransport transport = new ResultTransport();
    if (employJobType.contains("zhuanche") && (employJobStatus == 1 || employJobStatus == -1)
        && employStatus == 1) { // 包含专车业务,工作状态为专车或无任务,服务状态为空闲
      transport = zhuancheManager.grabV4(orderId, employId, employName, employPhone, companyId,
              employAccount, employPhoto, employScore, employName, rentalCompanyId, rentalCompanyName, appKey);

      if (transport.getCode() == 0) {
        transport = daijiaApi.pushJiedanV4(wxApplication.getAddress(), orderId, employId);
      }
    } else {
      transport.setCode(-21);
      transport.setMessage("服务人员状态错误");
    }
    return transport;


  }
  
  /**
   * 预约用车司机-我来做.
   */
  @RequestMapping(value = {"yuyueDriverDo"}, method = RequestMethod.POST)
  public ResultTransport yuyueDriverDo(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employToken") String employToken,
      @RequestParam("appKey") String appKey) {

    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    
    ResultTransport employResult =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    Long employId = Long.valueOf(emap.get("employId").toString());

    ResultTransport instanceResult = zhuancheManager.yuyueDriverDo(orderId, employId, appKey, wxApplication.getAddress());

    return instanceResult;
  }

  /**
   * V4接单.
   */
  @RequestMapping(value = {"jiedan"}, method = RequestMethod.POST)
  public ResultTransport jiedan(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employToken") String employToken,
      @RequestParam("appKey") String appKey) {

      System.out.println(appKey);
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    
    ResultTransport employResult =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    Long employId = Long.valueOf(emap.get("employId").toString());

    ResultTransport instanceResult = zhuancheManager.jiedan(orderId, employId, appKey, wxApplication.getAddress());

    if (instanceResult.getCode() == 0) {
      instanceResult = daijiaApi.pushJiedanV4(wxApplication.getAddress(), orderId, employId);
    }
    return instanceResult;
  }

  /**
   * V4拒单.
   */
  @RequestMapping(value = {"refuse"}, method = RequestMethod.POST)
  public ResultTransport refuse(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employToken") String employToken, 
      @RequestParam("cause") String cause,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    Long employId = Long.valueOf(emap.get("employId").toString());

    String employName = (String) emap.get("employName");

    ResultTransport transport =
        zhuancheManager.refuse(orderId, employId, cause, employName, appKey);
    if (transport.getCode() == 0) {
      transport = daijiaApi.refuseOrderV4(wxApplication.getAddress(), orderId, employId, cause);
    }
    return transport;
  }

  /**
   * V4到达预约地开始等待.
   */
  @RequestMapping(value = {"wait"}, method = RequestMethod.POST)
  public ResultTransport wait(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employToken") String employToken,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    String employName = (String) emap.get("employName");

    ResultTransport transport = zhuancheManager.waitV4(orderId, employName, appKey, wxApplication.getAddress());

    if (transport.getCode() == 0) {
      transport = daijiaApi.pushWaitZhuanV4(wxApplication.getAddress(), orderId);// 到达预约地发短信
    }

    return transport;
  }

  /**
   * V4执行.
   */
  @RequestMapping(value = {"run"}, method = RequestMethod.POST)
  public ResultTransport runOrder(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employToken") String employToken,
      @RequestParam(required = false, value = "realStartAddress") String realStartAddress,//真实上车地
      @RequestParam(required = false, value = "realStartLat") Double realStartLat,//真实上车地纬度
      @RequestParam(required = false, value = "realStartLng") Double realStartLng,//真实上车地经度
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    String operator = (String) emap.get("employName");

    ResultTransport transport = zhuancheManager.runV4(orderId, operator, appKey,realStartAddress,realStartLat,realStartLng);

    if (transport.getCode() == 0) {
      transport = daijiaApi.pushRunOrderZhuanV4(wxApplication.getAddress(), orderId);
    }

    return transport;
  }

  /**
   * V4销单(仅限APP司机端).
   */
  @RequestMapping(value = {"cancel"}, method = RequestMethod.POST)
  public ResultTransport cancel(
      @RequestParam("orderId") Long orderId,
      @RequestParam("cause") String cause,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    ResultTransport transport = daijiaApi.cancelZhuancheOrderV4(
        wxApplication.getAddress(), orderId, cause);// 司机销单推送给客户,并退款

    return transport;
  }

  /**
   * V4修改专车订单目的地.
   */
  @RequestMapping(value = {"updateToPlace"}, method = RequestMethod.POST)
  public ResultTransport updateToPlace(
      @RequestParam("orderId") Long orderId,
      @RequestParam("toPlace") String toPlace,
      @RequestParam("longitude") Double longitude,
      @RequestParam("latitude") Double latitude,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    ResultTransport resultTransport = new ResultTransport();
    resultTransport = zhuancheManager.updateToPlace(orderId, toPlace, longitude, latitude, appKey);
    return resultTransport;
  }

  /**
   * V4专车单结算页面的数据.
   */
  @RequestMapping(value = {"completeTaskData"}, method = RequestMethod.GET)
  public ResultTransport completeTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport =
        daijiaApi.completeTaskZhuanV4(wxApplication.getAddress(), orderId);

    return resultTransport;
  }

  /**
   * V4确认专车订单费用的接口.
   * @param orderId 订单id
   * @param realCash 实付金额
   * @param guoluMoney 过路费
   * @param yuanchengMoney 远程费
   * @param otherMoney 其他费
   * @param mileage 里程
   * @param waitedTime 等待时间
   * @param travelTime 行驶时间
   * @param toPlace 实际目的地
   * @param toPlaceLng 目的地详情经度
   * @param toPlaceLat 目的地详情纬度
   * @param ksMileage 空驶里程
   * @param ddMileage 调度里程
   * @param commission 佣金
   * 
   */
  @RequestMapping(value = {"confirmTask"}, method = RequestMethod.POST)
  public ResultTransport confirmTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("realCash") Double realCash, 
      @RequestParam("guoluMoney") Double guoluMoney,
      @RequestParam("yuanchengMoney") Double yuanchengMoney,
      @RequestParam("otherMoney") Double otherMoney,
      @RequestParam("mileage") Double mileage,
      @RequestParam("waitedTime") Integer waitedTime,
      @RequestParam("travelTime") Integer travelTime, 
      @RequestParam(required = false, value = "toPlace") String toPlace,
      @RequestParam(required = false, value = "toPlaceLng") Double toPlaceLng, 
      @RequestParam(required = false, value = "toPlaceLat") Double toPlaceLat,
      @RequestParam("startPrice") Double startPrice,
      @RequestParam("mileagePrice") Double mileagePrice,
      @RequestParam("runTimePrice") Double runTimePrice, 
      @RequestParam(required = false, value = "waitPrice") Double waitPrice,
      @RequestParam(required = false, value = "memo") String memo,
      @RequestParam(required = false, value = "jsonLocs") String jsonLocs, 
      @RequestParam(required = false, value = "ksMileage") Double ksMileage,
      @RequestParam(required = false, value = "ddMileage") Double ddMileage,
      @RequestParam(required = false, value = "commission") Double commission,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport =
        daijiaApi.confirmTaskZhuanV4(wxApplication.getAddress(), orderId, realCash, guoluMoney,
            yuanchengMoney, otherMoney, mileage, waitedTime, travelTime, toPlace, toPlaceLng,
            toPlaceLat, startPrice, mileagePrice, runTimePrice, waitPrice, memo, jsonLocs,
            ksMileage, ddMileage,commission);

    return resultTransport;
  }

  /**
   * V4实时获取订单是否被结算.
   */
  @RequestMapping(value = {"checkTask"}, method = RequestMethod.GET)
  public ResultTransport checkTask(@RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {

    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport =
        daijiaApi.checkTaskZhuanV4(wxApplication.getAddress(), orderId);

    return resultTransport;
  }

  /**
   * V4最后结算接口.
   * @param payType 支付类型: helppay(代付) sign(签单) balance(余额)
   */
  @RequestMapping(value = {"finishTask"}, method = RequestMethod.POST)
  public ResultTransport finishTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("payType") String payType,
      @RequestParam(required = false, value = "who") String who,
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport =
        daijiaApi.finishTaskZhuanV4(wxApplication.getAddress(), orderId, payType, who);
    return resultTransport;
  }

  /**
   * V4专车补单(APP暂时未用!).
   */
  @RequestMapping(value = {"createmore"}, method = RequestMethod.POST)
  public ResultTransport createmore(
      @RequestParam("employToken") String employToken, 
      @RequestParam(
      required = false, value = "passengerName") String passengerName,
      @RequestParam("passengerPhone") String passengerPhone,
      @RequestParam("carTypeId") Long carTypeId, 
      @RequestParam("startAddress") String startAddress,
      @RequestParam("startLat") Double startLat, 
      @RequestParam("startLng") Double startLng,
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam(required = false, value = "endLat") Double endLat,
      @RequestParam(required = false, value = "endLng") Double endLng, 
      @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    ResultTransport transport =
        daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (transport.getCode() == 0) {

      Map<String, Object> emap = (Map<String, Object>) transport.getData();

      Long employId = Long.valueOf(emap.get("employId").toString());
      Long employCompanyId = Long.valueOf(emap.get("companyId").toString());
      Double employScore = Double.valueOf(emap.get("employScore").toString());
      String employName = (String) emap.get("employName");
      String employPhone = (String) emap.get("employPhone");
      String employAccount = (String) emap.get("employAccount");
      String employPhoto = (String) emap.get("employPhoto");
      Double employLat = Double.valueOf(emap.get("employLat").toString());
      Double employLng = Double.valueOf(emap.get("employLng").toString());

      String employCompanyName = (String) emap.get("companyAbbreviation");


      int employJobStatus = (int) emap.get("employJobStatus");
      int employStatus = (int) emap.get("employStatus");
      String employJobType = (String) emap.get("employJobType");
      Long passengerId = null;
      passengerPhone = passengerPhone.replaceAll("-", "").replaceAll(" ", "");
      if (employJobType.contains("zhuanche") && (employJobStatus == 1 || employJobStatus == -1)
          && employStatus != 1) { // 包含专车业务,工作状态为专车或无任务,服务状态为空闲
        transport = passengerApi.findOneV4(passengerPhone, appKey);
        if (transport.getCode() == 0) { // 老客户
          Map<String, Object> map = (Map<String, Object>) transport.getData();
          passengerId = Long.valueOf(map.get("passengerId").toString());
          if (null != map.get("passengerName")) {
            passengerName = map.get("passengerName").toString();
          }
        } else {
          transport =
              passengerApi.createPassengerV4(passengerPhone, passengerName, employCompanyId,
                  employCompanyName, "司机补单", appKey);// 创建客户
          if (transport.getCode() == 0) {
            Map<String, Object> map = (Map<String, Object>) transport.getData();
            passengerId = Long.valueOf(map.get("passengerId").toString());
            passengerName = map.get("passengerName").toString();
            passengerPhone = map.get("passengerPhone").toString();
            if (passengerId != null) {
              daijiaApi.newPassengerActivityV4(wxApplication.getAddress(), passengerId);
            }
          } else {
            return transport;
          }
        }

        List<Coupon> coupons = null;
        ResultTransport resultTransport =
            salesApi.findByPassengerIdV4(passengerId, "zhuanche", appKey);
        if (resultTransport.getCode() == 0) {
          coupons = (List<Coupon>) resultTransport.getData();
        }
        Long couponId = null;
        if (coupons != null && coupons.size() != 0) {
          couponId = coupons.get(0).getId();// 自动取第一张优惠券使用
        }
        ResultTransport resultTransport2 = zhuancheManager.queryOneType(carTypeId, appKey);
        if (resultTransport2.getCode() == 0) {
          Map<String, Object> map = (Map<String, Object>) resultTransport2.getData();
          Long areaId = Long.valueOf(map.get("areaId").toString());

          Double shouldPay = 0.0;
          Double mileage = 0.0;
          Integer travelTime = 0;
          Double startPrice = 0.0;
          Double mileagePrice = 0.0;
          Double travelTimePrice = 0.0;

          ResultTransport transport2 =
              daijiaApi.getPriceByAreaIdV4(wxApplication.getAddress(), areaId, startLat, startLng,
                  endLat, endLng);
          if (transport2.getCode() == 0) {
            Map<String, Object> pmap = (Map<String, Object>) transport2.getData();
            shouldPay = Double.valueOf(pmap.get("money").toString());
            mileage = Double.valueOf(pmap.get("mileage").toString());
            travelTime = Integer.valueOf(pmap.get("time").toString());
            startPrice = Double.valueOf(pmap.get("startPrice").toString());
            mileagePrice = Double.valueOf(pmap.get("mileagePrice").toString());
            travelTimePrice = Double.valueOf(pmap.get("travelTimePrice").toString());
          }
          transport =
              zhuancheManager.createmoreV4(passengerPhone, carTypeId, startAddress, startLat,
                  startLng, employId, employName, employPhone, employCompanyId, appKey);

          if (transport.getCode() == 0) {
            Map<String, Object> map2 = (Map<String, Object>) transport.getData();
            Long orderId = Long.valueOf(map2.get("orderId").toString());
            daijiaApi.pushJiedanV4(wxApplication.getAddress(), orderId, employId);
          }

          return transport;
        } else {
          return resultTransport2;
        }

      } else {
        transport.setCode(-21);
        transport.setMessage("服务人员状态错误");
        return transport;
      }
    } else {
      return transport;
    }
  }
  
  /**
   * 预约订单查询.
   */
  @RequestMapping(value = {"findByParamsInBook"}, method = RequestMethod.GET)
  public ResultTransport findByParamsInBook(
	  @RequestParam(required = false, value = "page") Integer page,
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam(required = false, value = "latitude") Double latitude,
      @RequestParam(required = false, value = "longitude") Double longitude,
      @RequestParam(required = false, value = "carTypeId") Integer carTypeId,
      @RequestParam("appKey") String appKey) {

    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    
    ResultTransport instanceResult = zhuancheManager.findByParamsInBook(page, rows, latitude, longitude, wxApplication.getAddress(), carTypeId, appKey);

    return instanceResult;
  }
  
  /**
   * 预约订单总数.
   */
  @RequestMapping(value = {"countByParamsInBook"}, method = RequestMethod.GET)
  public ResultTransport countByParamsInBook(
      @RequestParam(required = false, value = "latitude") Double latitude,
      @RequestParam(required = false, value = "longitude") Double longitude,
      @RequestParam(required = false, value = "carTypeId") Integer carTypeId,
      @RequestParam("appKey") String appKey) {

    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    
    ResultTransport instanceResult = zhuancheManager.countByParamsInBook(latitude, longitude, wxApplication.getAddress(), carTypeId, appKey);

    return instanceResult;
  }
}
